﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DSS_XNA.Engine.Error;

namespace DSS_XNA.Engine.Entities
{
    public static class EntityManager
    {
        #region Properties

        public static Dictionary<Guid, Entity> Entities
        {
            get { return EntityManager._entities; }
            set { EntityManager._entities = value; }
        }
        private static Dictionary<Guid, Entity> _entities = new Dictionary<Guid, Entity>();

        #endregion

        public static void Add(Entity entity)
        {
            if (entity == null)
                throw new DSSException("'entity' is null.");

            if (Entities.ContainsKey(entity.Id))
                throw new DSSException(String.Format("An entity with the id '{0}' already exists.",
                    entity.Id));

            string name = entity.Name.Trim().ToLower();
            if (!String.IsNullOrEmpty(name))
            {
                var e = (from ent in Entities
                         where ent.Value.Name.Trim().ToLower() == name
                         select ent.Value).SingleOrDefault();

                if (e != null)
                {
                    Remove(e);
                }
            }

            Entities.Add(entity.Id, entity);
        }

        public static Entity Get(string name)
        {
            if (name == null)
                throw new DSSException("'name' is null.");
            if (name.Length == 0)
                throw new DSSException("'name' is zero-length.");

            name = name.ToLower().Trim();

            Entity e = null;

            foreach (Entity entity in Entities.Values)
            {
                if (entity.Name.ToLower().Trim() == name)
                {
                    e = entity;
                    break;
                }
            }

            if (e == null)
                throw new DSSException(String.Format("Failed to find entity with name '{0}'",
                    name));

            return e;
        }

        public static void Remove(Entity entity)
        {
            if (entity == null)
                throw new DSSException("'entity' is null.");

            if (Entities.ContainsKey(entity.Id))
            {
                Entities.Remove(entity.Id);
            }
        }
    }
}
